# 新增：从 random 模块中导入 sample 函数

# 新增：从 extensions 模块中导入 db
from flask import current_app  # 新增：导入 current_app
from sqlalchemy.exc import SQLAlchemyError  # 新增：导入 SQLAlchemyError

from data_modules.database_handler import DatabaseHandler  # 新增导入
from data_modules.models import Attraction  # 修正为正确的模块路径
from utils.baidu_map_api import BaiduMapAPI  # 修改为正确的模块路径


class AlgorithmService:
    def __init__(self):
        self.baidu_map_api = BaiduMapAPI(api_key=current_app.config.get('BAIDU_MAP_API_KEY'))
        self.attraction_handler = DatabaseHandler(Attraction)  # 新增数据库处理器

    def _random_select_within_budget(self, attractions, budget):
        """
        使用动态规划算法精确匹配总预算
        :param attractions: 景点列表
        :param budget: 总预算
        :return: 预算总和精确匹配的景点组合
        """
        dp = [[] for _ in range(budget + 1)]
        for attraction in attractions:
            cost = int(attraction.budget)
            for i in range(budget, cost-1, -1):
                if dp[i - cost] and (len(dp[i]) < len(dp[i - cost]) + 1):
                    dp[i] = dp[i - cost] + [attraction]
            if cost <= budget and (not dp[cost] or len(dp[cost]) > 1):
                dp[cost] = [attraction]

        valid_combinations = [combo for total, combo in enumerate(dp) if total == budget and combo]
        if not valid_combinations:
            return []
        return choice(valid_combinations)

    def _extract_coordinates(self, attractions):
        """提取景点经纬度集合"""
        return [{"latitude": attr.latitude, "longitude": attr.longitude} for attr in attractions]

    def calculate_route(self, interests, budget, time, route_type):
        """
        根据用户提交的数据和数据库中的景点信息，计算推荐路线。
        """
        try:


            # 构建分类条件
            categories = [
                category for interest, category in zip(
                    ['历史文化', '自然风光', '美食购物', '综合'],
                    ['历史文化', '自然风光', '美食购物', '综合']  # 修正分类参数
                ) if interest in interests
            ]

            # 添加默认分类处理
            if not categories:
                return {"error": "请选择至少一个兴趣分类。"}

            # 使用新的数据库处理模块
            attractions = self.attraction_handler.build_query(
                categories=categories,
                order_by='popularity'
            ).get_all()


            if not attractions:
                return {
                    "error": "未找到符合条件的景点，请调整预算或兴趣选项。"
                }

            # 删除旧的查询逻辑

            # 随机选择景点以满足预算
            selected_attractions = self._random_select_within_budget(attractions, budget)
            if not selected_attractions:
                return {
                    "error": "无法在预算范围内找到合适的景点组合。"
                }

            # 计算总费用并提取经纬度数据
            total_budget = sum(attraction.budget for attraction in selected_attractions)
            locations = self._extract_coordinates(selected_attractions)
            attraction_details = [
                {
                    "name": getattr(attraction, 'attraction_name', ''),
                    "e_name": getattr(attraction, 'e_name', ''),
                    "latitude": getattr(attraction, 'latitude', 0.0),
                    "longitude": getattr(attraction, 'longitude', 0.0)
                }
                for attraction in selected_attractions
            ]

            # 调用百度地图API生成路线URL
            origin = f"{locations[0]['latitude']},{locations[0]['longitude']}"
            destination = f"{locations[-1]['latitude']},{locations[-1]['longitude']}"
            
            current_app.logger.debug(f"地图API参数 - 起点: {origin}, 终点: {destination}, 类型: {route_type}")

            if route_type == 'riding':
                route_url = self.baidu_map_api.get_riding_direction_url(origin, destination)
            elif route_type == 'driving':
                route_url = self.baidu_map_api.get_driving_direction_url(origin, destination)
            elif route_type == 'walking':
                route_url = self.baidu_map_api.get_walking_direction_url(origin, destination)
            else:
                route_url = self.baidu_map_api.get_driving_direction_url(origin, destination)

            return {
                "route_description": f"推荐路线：从{attraction_details[0]['name']}到{attraction_details[-1]['name']}",
                "attraction_details": attraction_details,
                "cost_breakdown": total_budget,  # 修正为使用total_budget
                "route_url": route_url
            }

        except SQLAlchemyError as e:
            current_app.logger.error(f"数据库查询失败: {str(e)}")
            return {
                "error": "数据库查询失败，请稍后重试。"
            }
        except Exception as e:
            current_app.logger.error(f"计算路线失败: {str(e)}")
            return {
                "error": "系统错误，请稍后重试。"
            }
